package middleware

import (
	"resource_web/ginx/errormessage"
	"resource_web/ginx/helper"
	"time"

	"github.com/gin-gonic/gin"
)

func JWT() gin.HandlerFunc {
	return func(context *gin.Context) {
		var code int
		var data interface{}
		code = 200
		token := context.GetHeader("Authorization")
		if token == "" {
			code = 404
		} else {
			claims, err := helper.AnalyzeToken(token)
			if err != nil {
				code = errormessage.ErrorAuthCheckTokenFail
			} else if time.Now().Unix() > claims.ExpiresAt {
				code = errormessage.ErrorAuthCheckTokenTimeout
			}
		}
		if code != errormessage.SUCCESS {
			context.JSON(200, gin.H{
				"status": code,
				"msg":    errormessage.GetMsg(code),
				"data":   data,
			})
			context.Abort()
			return
		}
		context.Next()
	}
}
